Ext.namespace("MyApp.common"); // For the stuff added below

// Common setting changes of Ext JS
Ext.tip.QuickTipManager.init();
Ext.Msg.maxWidth = 1024;
Ext.form.Field.prototype.msgTarget = 'under';
Ext.Ajax.disableCaching = false;
//Ext.state.Manager.setProvider(new Ext.state.CookieProvider());

if (typeof console === "undefined") {
  console = {
      log: function () {
        // do nothing
      }
  };
}

Ext.getUrlParam = function(param) {
   var params = Ext.urlDecode(location.search.substring(1));
   return param ? params[param] : params;
};

Ext.getHashParam = function(param) {
  var params = Ext.urlDecode(location.hash.substring(1));
  return param ? params[param] : params;
};

// Temporary fix to make Ext JS work with IE 9. I hope they will fix this in the next Ext JS version :)

//if ((typeof Range !== "undefined") && !Range.prototype.createContextualFragment)
//{
//    Range.prototype.createContextualFragment = function(html)
//    {
//        var frag = document.createDocumentFragment(), 
//        div = document.createElement("div");
//        frag.appendChild(div);
//        div.outerHTML = html;
//        return frag;
//    };
//}

// Common functions
MyApp.common.handleFormSubmit = function (url, id, nextPage) {
  return function (component, event) {
    component.ownerCt.ownerCt.getForm().submit({
      waitTitle: 'Please wait...',
      waitMsg:'Sending data...',
      method: id==null?"POST":"PUT",
      url: url + (id==null?"":"/"+encodeURIComponent(id)),
      headers: { "Accept": "application/json" },
      success: function(form, action) {
        MyApp.common.goToNextPage(nextPage);
      },
      failure: MyApp.common.handleFormSubmitFailure
    });
  };
};

MyApp.common.handleFormSubmitFailure = function (form, action) {
  switch (action.failureType) {
    case Ext.form.Action.CLIENT_INVALID:
      Ext.Msg.alert('Failure: CLIENT_INVALID', 'Form fields may not be submitted with invalid values');
      break;
    case Ext.form.Action.CONNECT_FAILURE:
      MyApp.common.displayFailure('Failure: CONNECT_FAILURE', action.response);
      break;
    case Ext.form.Action.SERVER_INVALID:
      if(action.result.msg) {
        Ext.Msg.alert('Failure: SERVER_INVALID', '<b>'+action.result.msg+'</b>'+(action.result.longmsg?'<br>'+action.result.longmsg:''));
      }
      break;
    default:
      MyApp.common.displayFailure('Failure: default', action.response);
      break;
  }
};

MyApp.common.loadForm = function (formPanel, url, id, doOnSuccess) {
  if(id != null) {
    formPanel.getForm().load({
      url: url + '/' + encodeURIComponent(id),
      method: "GET",
      headers: { "Accept": "application/json" },
      waitMsg: 'Loading...',
      failure: MyApp.common.handleFormLoadFailure,
      success: doOnSuccess
    });
  }
};

MyApp.common.handleFormLoadFailure = function (form, action) {
  switch (action.failureType) {
    case Ext.form.Action.CONNECT_FAILURE:
      MyApp.common.displayFailure('Failure: CONNECT_FAILURE', action.response, function() {history.go(-1);});
      break;
    case Ext.form.Action.LOAD_FAILURE:
      MyApp.common.displayFailure('Failure: LOAD_FAILURE', action.response, function() {history.go(-1);});
      break;
    default:
      MyApp.common.displayFailure('Failure: default', action.response, function() {history.go(-1);});
      break;
  }
};

MyApp.common.handleStoreLoadException = function (dataProxy, response, operation) {
  MyApp.common.displayFailure('Failure', response);
};

MyApp.common.decodeJson = function (responseText) {
  try {
    return Ext.decode(responseText);
  } catch (Error) {
    //Ext.Msg.alert('Json parsing failed: ' + Error);
    return null;
  }
};

MyApp.common.displayFailure = function (title, response, doAfterMessage) {
  if(response.status == 401) {
    MyApp.common.removeCachedUserInfo();
    document.location = htmlPath + "/missing-role/missing-role.html";
  } else {
    title = title + " (" + response.status + " " + response.statusText + ")";
    
    if(response.responseText) {
      var jsonResponse = MyApp.common.decodeJson(response.responseText);
      
      if(jsonResponse != null) {
        if(jsonResponse.success) {
          Ext.Msg.alert('Ended up in Exception handler, despite success:true. Odd.', '<b>'+jsonResponse.msg+'</b>'+(jsonResponse.longmsg?'<br>'+jsonResponse.longmsg:''), doAfterMessage);
        } else if (jsonResponse.msg) {
          Ext.Msg.alert(title, '<b>'+jsonResponse.msg+'</b>'+(jsonResponse.longmsg?'<br>'+jsonResponse.longmsg:''), doAfterMessage);
        } else {
          Ext.Msg.alert(title, 'No reason given.', doAfterMessage);        
        }
      } else {
        new Ext.Window({
          x: 1,
          y: 1,
          title: title,
          html: response.responseText,
          listeners: {
            show: function (panel) {
              if(panel.getWidth() < Ext.getBody().getWidth() && panel.getHeight() < Ext.getBody().getHeight()) {
                panel.center();
                Ext.getBody().mask();
              }
            },
            close: function () {
              Ext.getBody().unmask();
            }
          }
        }).show();
      }
    } else {
      Ext.Msg.alert(title, "No responseText", doAfterMessage);
    }
  }
};

MyApp.common.submitWithEnterFormFieldDefault = function(buttonId) {
  return {
    enableKeyEvents:true,
    listeners: {
      specialKey: function(field, el) {
        if(el.getKey() == Ext.EventObject.ENTER) {
          var submitButton = Ext.getCmp(buttonId);
          submitButton.handler(submitButton);
        }
      }
    }
  };
};

MyApp.common.sendJsonRequestAndDoOnSuccess = function (config, doThisOnSuccess, doThisOnFailure) {
  var defaultConfig = {
    headers: { "Accept": "application/json" },
    loadIndicator: true,
    delayLoadIndicator: typeof config.method == "undefined" && typeof config.params == "undefined" || typeof config.method != "undefined" && config.method == "GET",
    
    messageBeforeSuccessAction: true,
    messageBeforeFailureAction: true,
    success: function(response, opts) {
      hideLoadIndicator();
      
      var jsonResponse = MyApp.common.decodeJson(response.responseText);

      if(jsonResponse != null) {
        if(jsonResponse.success) {
          if(jsonResponse.msg) {
            Ext.Msg.alert('Success', '<b>'+jsonResponse.msg+'</b>'+(jsonResponse.longmsg?'<br>'+jsonResponse.longmsg:''), function() {
              if(doThisOnSuccess && messageBeforeSuccessAction) {
                doThisOnSuccess(jsonResponse, response, opts);
              }
            });
          }
          
          if(doThisOnSuccess && (!messageBeforeSuccessAction || !jsonResponse.msg)) {
            doThisOnSuccess(jsonResponse, response, opts);
          }
        } else {
          if(jsonResponse.msg) {
            Ext.Msg.alert('Failure ' + opts.url, '<b>'+jsonResponse.msg+'</b>'+(jsonResponse.longmsg?'<br>'+jsonResponse.longmsg:''), function() {
              if(doThisOnFailure && messageBeforeFailureAction) {
                doThisOnFailure(jsonResponse, response, opts);
              }
            });
          }

          if(doThisOnFailure && (!messageBeforeFailureAction || !jsonResponse.msg)) {
            doThisOnFailure(jsonResponse, response, opts);
          }
        }
      } else {
        if(doThisOnFailure && !messageBeforeFailureAction) {
          doThisOnFailure(null, response, opts);
        }
        MyApp.common.displayFailure('Failure ' + opts.url, response, function () {
          if(doThisOnFailure && messageBeforeFailureAction) {
            doThisOnFailure(null, response, opts);
          }
        });
      }
    },
    failure: function (response, opts) {
      if(doThisOnFailure && !messageBeforeFailureAction) {
        doThisOnFailure(null, response, opts);
      }
      
      hideLoadIndicator();

      MyApp.common.displayFailure('Failure: ' + opts.url, response, function () {
        if(doThisOnFailure && messageBeforeFailureAction) {
          doThisOnFailure(null, response, opts);
        }
      });
    }
  };
  
  var loadMaskDelayer = null;
  var loadMask = null;
  
  var hideLoadIndicator = function() {
    if(loadMaskDelayer != null) {
      clearTimeout(loadMaskDelayer);
    }
    
    if(loadMask != null) {
      loadMask.disable();
    }
  };
  
  var actualConfig = {};
  Ext.apply(actualConfig, config, defaultConfig);

  if(typeof actualConfig.loadIndicator != "undefined" && actualConfig.loadIndicator != null && actualConfig.loadIndicator != false) {
    var loadIndicatorTarget = actualConfig.loadIndicator == true?Ext.getBody():actualConfig.loadIndicator;
    
    function showLoadMask() {
      loadMask = new Ext.LoadMask(loadIndicatorTarget, {
        msg: 'Working...'
      });
      loadMask.show();
    }
    
    if (actualConfig.delayLoadIndicator == true) {
      loadMaskDelayer = setTimeout(showLoadMask, 1000);
    } else {
      showLoadMask();
    }
  }
  
  actualConfig.loadIndicator = null;

  var messageBeforeSuccessAction = actualConfig.messageBeforeSuccessAction;
  var messageBeforeFailureAction = actualConfig.messageBeforeFailureAction;
  actualConfig.messageBeforeSuccessAction = null;
  
  Ext.Ajax.request(actualConfig);
};

MyApp.common.sendJsonRequestThenGoToNewPage = function (config, nextPage) {
  MyApp.common.sendJsonRequestAndDoOnSuccess(config, function (jsonResponse) {
    MyApp.common.goToNextPage(nextPage);
  });
};

MyApp.common.goToNextPage = function (nextPage) {
  Ext.Msg.wait("Loading next page...", "Please Wait...");
  document.location.replace(nextPage);
};

MyApp.common.getAttributeNSAsInt = function (element, ns, id) {
  var result = element.getAttributeNS(ns, id);
  if (result != null) {
    return parseInt(result);
  } else {
    return null;
  }
};

MyApp.common.makeHtml = function (text) {
  return Ext.htmlEncode(text).replace(/\n\n/g, '<p></p>').replace(/\n/g, "<br>");
};

//
